package cn.stylefeng.guns.rabbitmq.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.util.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.util.Base64Utils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;

/**
 * HTTP请求工具类
 *
 * @author tandk
 * @date 2017/10/20 0020 下午 14:49
 */
public class HttpUtil {
    /**
     * 发送GET请求
     *
     * @param url     目的地址
     * @param charset 编码字符集
     * @return 远程响应结果
     */
    public static String sendGet(String url, String charset) throws IOException {
        String result = null;
        HttpClient httpclient = HttpClients.createDefault();
        HttpGet httpget = new HttpGet(url);
        HttpResponse response = httpclient.execute(httpget);
        if (response != null) {
            HttpEntity resEntity = response.getEntity();
            if (resEntity != null) {
                result = EntityUtils.toString(resEntity, charset);
            }
        }
        return result;
    }

    /**
     * 发送POST请求
     *
     * @param url     目的地址
     * @param map     请求参数
     * @param charset 编码字符集
     * @return 远程响应结果
     */
    public static String sendPost(String url, Map<String, String> map, String charset) throws IOException {
        String result = null;
        HttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        // 设置参数
        List<NameValuePair> list = new ArrayList<NameValuePair>();
        Iterator iterator = map.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, String> elem = (Map.Entry<String, String>) iterator
                    .next();
            list.add(new BasicNameValuePair(elem.getKey(), elem.getValue()));
        }
        UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(list, charset);
        httpPost.setEntity(uefEntity);
        HttpResponse response = httpClient.execute(httpPost);
        if (response != null) {
            HttpEntity resEntity = response.getEntity();
            if (resEntity != null) {
                result = EntityUtils.toString(resEntity, charset);
            }
        }
        return result;
    }

    public static String sendPostJson(String url, String body,  String charset) throws IOException {
        String result = null;
        HttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        // 设置参数
        List<NameValuePair> list = new ArrayList<NameValuePair>();
        httpPost.addHeader("Content-Type", "application/json");
        httpPost.setEntity(new StringEntity(body, "utf-8"));
        HttpResponse response = httpClient.execute(httpPost);
        if (response != null) {
            HttpEntity resEntity = response.getEntity();
            if (resEntity != null) {
                result = EntityUtils.toString(resEntity, charset);
            }
        }
        return result;
    }

    /**
     * 发送POST请求
     *
     * @param url     目的地址
     * @param headers 头地址
     * @param map     请求参数
     * @param charset 编码字符集
     * @return 远程响应结果
     */
    public static String sendPostAndHeader(String url, Map<String, String> headers, Map<String, Object> map, String charset) throws IOException {
        String result = null;
        HttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        // 设置参数
        List<NameValuePair> list = new ArrayList<NameValuePair>();
        Iterator iterator = map.entrySet().iterator();
        while (iterator.hasNext()) {

            Map.Entry<String, Object> elem = (Map.Entry<String, Object>) iterator
                    .next();
            if (elem.getValue().getClass().isArray()) {
                list.add(new BasicNameValuePair(elem.getKey(), JSONArray.toJSONString(elem.getValue())));
            } else {
                list.add(new BasicNameValuePair(elem.getKey(), String.valueOf(elem.getValue())));
            }
        }
        for (String key : headers.keySet()) {
            httpPost.setHeader(key, headers.get(key));
        }
        UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(list, charset);
        httpPost.setEntity(uefEntity);
        HttpResponse response = httpClient.execute(httpPost);
        if (response != null) {
            HttpEntity resEntity = response.getEntity();
            if (resEntity != null) {
                result = EntityUtils.toString(resEntity, charset);
            }
        }
        return result;
    }

    /**
     * 获取完整url带参数
     */
    public static String getFullUrl(HttpServletRequest request) {
        String url = request.getRequestURL().toString();
        String fullUrl = url;
        StringBuilder paramUrl = new StringBuilder();
        Map<String, String[]> map = request.getParameterMap();
        if (map != null) {
            if (!map.isEmpty()) {
                Set<Map.Entry<String, String[]>> set = map.entrySet();
                Iterator<Map.Entry<String, String[]>> it = set.iterator();
                while (it.hasNext()) {
                    Map.Entry<String, String[]> entry = it.next();
                    paramUrl.append("&");
                    paramUrl.append(entry.getKey());
                    paramUrl.append("=");
                    String value = "";
                    for (String v : entry.getValue()) {
                        value = value + v;
                    }
                    paramUrl.append(value);
                }
                fullUrl = fullUrl + "?" + paramUrl.toString().replaceFirst("&", "");
            }
        }
        return fullUrl;
    }

    /**
     * 获取请求中参数
     */
    public static Map<String, String[]> getParamMap(HttpServletRequest request) {
        Map<String, String[]> map = request.getParameterMap();
        if (map != null) {
            if (!map.isEmpty()) {
                Set<Map.Entry<String, String[]>> set = map.entrySet();
                Iterator<Map.Entry<String, String[]>> it = set.iterator();
                while (it.hasNext()) {
                    Map.Entry<String, String[]> entry = it.next();
                    String value = "";
                    for (String v : entry.getValue()) {
                        value = value + v;
                    }
                }
            }
        }
        return map;
    }

    /**
     * 获取真实ip地址
     *
     * @param request
     * @return
     */
    public static String getRemoteHost(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        String unknown = "unknown";
        if (ip == null || ip.length() == 0 || unknown.equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || unknown.equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || unknown.equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
    }

    /*public static void main(String[] args) {
        String str = "rO0ABXNyAB9jb20uYWxpYmFiYS5mYXN0anNvbi5KU09OT2JqZWN0AAAAAAAAAAECAAFMAANtYXB0AA9MamF2YS91dGlsL01hcDt4cHNyABFqYXZhLnV0aWwu" +
                "SGFzaE1hcAUH2sHDFmDRAwACRgAKbG9hZEZhY3RvckkACXRocmVzaG9sZHhwP0AAAAAAAAx3CAAAABAAAAADdAAJb3JkZXJJdGVtc3IAF2phdmEudXRpbC5M" +
                "aW5rZWRIYXNoTWFwNMBOXBBswPsCAAFaAAthY2Nlc3NPcmRlcnhxAH4AAz9AAAAAAAAYdwgAAAAgAAAADnQABmFtb3VudHNyABBqYXZhLmxhbmcuRG91Ymxl" +
                "gLPCSilr+wQCAAFEAAV2YWx1ZXhyABBqYXZhLmxhbmcuTnVtYmVyhqyVHQuU4IsCAAB4cEBo4AAAAAAAdAANY2FyZENhdGFvcnlJZHNyAA5qYXZhLmxhbmcu" +
                "TG9uZzuL5JDMjyPfAgABSgAFdmFsdWV4cQB+AAoP72Gu2WYQCHQAD2NhcmRDYXRhb3J5TmFtZXQADOS4reWbveenu+WKqHQABmNhcmROb3QAETEyMzIzMjMy" +
                "MzIxMzMxMzM0dAAMY2FyZFBhc3N3b3JkdAATMTIzMjMyMzIzMmZkZmcxMzI1NnQAC2NhcmRRdW90YUlkc3IAEWphdmEubGFuZy5JbnRlZ2VyEuKgpPeBhzgC" +
                "AAFJAAV2YWx1ZXhxAH4ACgAAAAJ0AA1jYXJkUXVvdGFOYW1ldAACMTB0AApjYXJkVHlwZUlkc3EAfgAND+9hrtlmEAJ0AAxjYXJkVHlwZU5hbWV0AAnor53o" +
                "tLnljaF0AApjcmVhdGVUaW1lc3EAfgANAAABbM0WZOd0AAlpdGVtUXVvdGFzcQB+ABYAAADIdAAHb3JkZXJJZHNxAH4AFgAAABF0AAtvcmRlckl0ZW1JZHNx" +
                "AH4AFgAAABB0AAhzdWJRdW90YXNxAH4AFgAAAMh4AHQAB2NoYW5uZWxzcQB+AAY/QAAAAAAADHcIAAAAEAAAAAx0AAdhcGlUeXBldAAEcG9zdHQABmFwaVVy" +
                "bHQALWh0dHA6Ly9hcGkuc3V4aWFva2EuY24vYXBpL2NhcmQvc3VibWl0Q2FyZC5kb3QACmNhdGVnb3J5SWRzcQB+AA0P72Gu2WYQCHQAC2NoYW5uZWxDb2Rl" +
                "dAAOcmVuQ2FyZFNlcnZpY2V0AAtjaGFubmVsTmFtZXQAGOS6uuS6uumUgOWNoeS4reWbveenu+WKqHEAfgAec3EAfgANAAABbJSe3Rh0AApkZWxldGVGbGFn" +
                "c3EAfgAWAAAAAHQABnBhcmFtc3QA2lt7IkxBWV9UQUJMRV9JTkRFWCI6MCwibmFtZSI6IuS6p+WTgee8luWPtyIsImtleSI6InByb2R1Y3RDb2RlIiwidmFs" +
                "dWUiOiJNT0JJTEUifSx7IkxBWV9UQUJMRV9JTkRFWCI6MSwibmFtZSI6IuWbnuiwg+WcsOWdgCIsImtleSI6ImNhbGxiYWNrVVJMIiwidmFsdWUiOiJodHRw" +
                "Oi8vNDcuOTYuMjM2LjcxOjMwMTE2L3JhYmJpdG1xL2NhcmQvbm90aWZ5L3JlbkNhcmRTZXJ2aWNlIn1ddAAMcGluQ2hhbm5lbElkc3EAfgAWAAAAA3QABnJl" +
                "bWFya3QADOS6uuS6uumUgOWNoXQABnN0YXR1c3NxAH4AFgAAAAF0AAp1cGRhdGVUaW1lc3EAfgANAAABbMz9Akh4AHQABW9yZGVyc3EAfgAGP0AAAAAAAAx3" +
                "CAAAABAAAAAMcQB+AAhzcQB+AAlAaOAAAAAAAHQACmNvc3RBbW91bnRzcQB+AAlAaPMzMzMzM3QACGNvc3RSYXRlc3EAfgAJP+/vnbItDlZxAH4AHnNxAH4A" +
                "DQAAAWzNFmQNdAAMZXhwZWN0UHJvZml0c3EAfgAJP+MzMzMzMzNxAH4AInEAfgAjdAAHb3JkZXJOb3QAGkxYMjAxOTA4MjYxNjQxMzI2MzQ3NDY5MTExdAAJ" +
                "b3duZXJVc2VydAAEMTg4MnQAC293bmVyVXNlcklkc3EAfgANEBRWuTsLgAF0AAlwYXlBbW91bnRzcQB+AAlAaOAAAAAAAHQAB3BheVJhdGVzcQB+AAk/77ZF" +
                "ocrAg3QABXF1b3Rhc3EAfgAWAAAAyHgAeA==";
        InputStream in = new ByteArrayInputStream(IOUtils.decodeBase64(str));
        ObjectInputStream ins = null;
        try {
            ins = new ObjectInputStream(in);
            JSONObject obj = (JSONObject)ins.readObject();
            System.out.println(obj.toJSONString());
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

    }*/
}
